<template>
	<view class="center">
		<view class="bgc">
			<image :src="backGround" mode="widthFix" class="bac-sty"></image>
		</view>

		<view class="chet_wrap">
			<view class="shop_wrap">
				<image src="../../static/default-avatar.png" mode="aspectFill" class="shop_img"></image>
			</view>
			<view class="shop_name">
				美传
			</view>
			<view class="shop-tel">
				{{phone || ''}}
			</view>
			<view class="shop_desc">
				未注册号码将自动创建账号
			</view>


			<button class="shop-btn" type="success" @click="getPhoneNumber" :disabled="loading"
				:loading="loading">本机号码一键登录</button>


			<view v-if="phoneType=='ios'" class="btn-wrap" @click="getPhoneIOS">
				<view class="btn-ios">
					<image src="@/static/user/ios.png" mode="" class="ios-sty"></image>
					<view class="">
						Apple登录
					</view>
				</view>
			</view>



			<checkbox-group class="shop-check" @change="onCheck">
				<label>
					<checkbox value="cb" color="#FFCC33" style="transform:scale(0.7)" />
				</label>
				<text>登录即表示同意</text><text class="color_bule">
					<a href="https://www.yuque.com/fangaodeyouer/iys6kb/cc2eqt60g2sy2zlr?singleDoc#">《用户协议》</a>
				</text>和
				<a href="https://www.yuque.com/fangaodeyouer/iys6kb/snzy7w3rm0cg4i6r?singleDoc# ">《隐私政策》</a>
			</checkbox-group>
		</view>

		<on-loading :loading="loading" :text="text"></on-loading>
		<u-modal :show="showing" @confirm="confirmBtn">
			<view class="slot-content">
				<view class="title">
					请绑定手机号
				</view>
				<view class="phonePut">
					<u-input v-model="phonePut" :type="'text'" :border="'false'" />
				</view>
			</view>
		</u-modal>
		<InviteDia ref="inviteDia" />
	</view>
</template>

<script>
	import InviteDia from "@/components/inviteDia/inviteDia.vue"
	import {
		mapState,
		mapMutations
	} from "vuex"

	import {
		login,
		getStoreId,
		addCart,
		getCodeItem,
		login4ios,
		loginIosCheck
	} from "@/api/apis.js";
	export default {
		components: {
			InviteDia
		},
		data() {
			return {
				phone: "",
				word: "",
				messageText: "",
				loading: false,
				status: [],
				text: "登录中",
				phoneType: null,
				backGround: "https://guanshi-app.oss-cn-qingdao.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240730091948.png",
				showing: false,
				phonePut: '',
				openids: '',
				location: null,
			};
		},
		onLoad(e) {
			this.word = e.word || ''
		},

		created() {
			// #ifdef APP-PLUS
			if (plus.os.name === 'iOS') {
				// iOS平台的处理逻辑
				this.phoneType = 'ios'

			} else if (plus.os.name === 'Android') {
				// Android平台的处理逻辑
				console.log('Android平台的处理');
				this.phoneType = null
			}
			// #endif
		},
		onShow() {
			if (this.$refs.inviteDia) {
				this.$refs.inviteDia.getClipboardData()
			}
			this.getLocation()
			uni.clearStorageSync('identify') //清空当前登录用户信息
		},
		methods: {
			...mapMutations("userInfo", ["setToken", 'setUserInfo', 'setStoreId', 'setStoreForm']),
			// ...mapMutations("userInfo", ['setOpid'])
			getLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.location = {
							latitude: res.latitude,
							longitude: res.longitude,
							speed: res.speed,
							accuracy: res.accuracy,
						};
						console.log(this.location, 'this.location')
						// this.reverseGeocode(res.latitude, res.longitude);
						console.log('定位成功:', res);
					},
					fail: (err) => {
						this.error = err;
						console.error('定位失败:', err);
					}
				});
			},
			onCheck(e) {
				this.status = e.target.value
			},

			// 手机号一键登录
			getPhoneNumber() {
				if (this.status.length == 0) {
					uni.showToast({
						title: '请勾选用户协议',
						icon: 'none',
						duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
						mask: true, // 是否显示透明蒙层， 防止触摸穿透， 默认： false
					});
					return false
				}
				let that = this
				that.loading = true
				uni.preLogin({ //预登陆检查是否符合一键登录的环境，可不用
					provider: 'univerify',
					success: () => {
						uni.login({
							provider: 'univerify',
							univerifyStyle: {
								"fullScreen": false, // 是否全屏显示，true表示全屏模式，false表示非全屏模式，默认值为false。
								"backgroundColor": "#ffffff", // 授权页面背景颜色，默认值：#ffffff  
								"phoneNum": {
									"color": "#000000", // 手机号文字颜色 默认值：#000000   
								},
								"slogan": {
									"color": "#8a8b90", //  slogan 字体颜色 默认值：#8a8b90  
								},
								"icon": {
									"path": "static/logo.png" // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo   
								},
								"authButton": {
									"normalColor": "#3479f5", // 授权按钮正常状态背景颜色 默认值：#3479f5  
									"highlightColor": "#2861c5", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）  
									"disabledColor": "#73aaf5", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）  
									"textColor": "#ffffff", // 授权按钮文字颜色 默认值：#ffffff  
									"title": "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”  
								},
								"otherLoginButton": {
									"visible": "false", // 是否显示其他登录按钮，默认值：true  
								},
							},
							success: (res) => {
								uniCloud.callFunction({
									name: 'getPhoneNumber', // 你的云函数名称
									data: {
										access_token: res.authResult
											.access_token, // 客户端一键登录接口返回的access_token
										openid: res.authResult.openid // 客户端一键登录接口返回的openid
									}
								}).then(dataRes => {
									console.log('云函数返回的参数', dataRes)
									this.phone = dataRes.result.data
										.phoneNumber //这里的dataRes.result.res就是前面云函数index中retrun的res(还包含其他信息，phoneNumber只是手机号)
									let prams = {
										mobile: this.phone,
										latitude: this.location.latitude,
										longitude: this.location.longitude
									};
									login(prams).then((res) => {
										// console.log(res);
										if (res.success) {
											let tabs = [{
													title: "美传自营店",
													id: 1,
												},
												// 可以继续添加更多的 Tab
											]
											let userInfo = res.result.userInfo
											console.log(res.result);
											console.log(userInfo);
											if (userInfo.belongStore == 1) {
												let item = {
													title: userInfo.storeName,
													id: userInfo.storeId
												}
												tabs.unshift(item)
											}
											this.setStoreForm(tabs)

											uni.showToast({
												title: '登录成功',
												icon: 'success',
												duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
												mask: true, // 是否显示透明蒙层， 防止触摸穿透， 默认： false
												// image:'./image.png',//自定义图标的本地路径
											});
											this.setToken(res.result.token);
											this.setUserInfo(res.result.userInfo);
											this.setStoreId(this.currentIndex) //


											// 授权虚拟用户信息
											let identify = 'tom';
											uni.setStorageSync('identify',
												identify);

											// console.log(this.word);
											if (this.word && this.word != 'null') {
												this.onGoodsDetail() //如果存在剪切板。调用接口绑定邀请码等信息
											} else {
												// console.log("执行跳转操作", userInfo
												// 	.belongStore);
												// console.log(userInfo);
												if (userInfo.belongStore != 1) {
													this.$refs.inviteDia.opens()
													this.$refs.inviteDia
														.getClipboardData()
												} else {
													uni.reLaunch({
														url: "/pages/index/index"
													})
												}
											}


										} else {
											this.$mesaage.error(res.result
												.message);
										}
									}).finally(() => {
										that.loading = false
									})

								}).catch(err => {
									that.loading = false
									console.log('云函数报错', err)
								})
								uni.showToast({
									title: res.authResult,
									icon: "none"
								})
								uni.closeAuthView() //关闭一键登录弹出窗口
							},
							fail(res) { // 登录失败
								uni.closeAuthView() //关闭一键登录弹出窗口
								that.loading = false
							},
						})
					},
					fail(res) {
						console.log('一键登录失败', res)
						if (res.errMsg != 'login:ok') {
							uni.showToast({
								title: res.metadata.msg,
								icon: "none"
							})
						}
						//如果手机没有插入有效的sim卡，或者手机蜂窝数据网络关闭，
						//都有可能造成预登录校验失败。
						this.loading = false
					}
				})
			},
			confirmBtn() {
				// console.log(e,'eeeeeeee')
				console.log(this.phonePut, 'phonePut');

				let prams = {
					mobile: this.phonePut,
					openId: this.openids,
					latitude: this.location.latitude,
					longitude: this.location.longitude
				};
				console.log(prams, 'prams')
				login4ios(prams).then((res) => {
					// console.log(res);
					if (res.success) {
						this.showing = false
						let tabs = [{
								title: "美传自营店",
								id: 1,
							},
							// 可以继续添加更多的 Tab
						]
						let userInfo = res.result.userInfo
						// console.log(res.result);
						// console.log(userInfo);
						if (userInfo.belongStore == 1) {
							let item = {
								title: userInfo.storeName,
								id: userInfo.storeId
							}
							tabs.unshift(item)
						}
						this.setStoreForm(tabs)

						uni.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
							mask: true, // 是否显示透明蒙层， 防止触摸穿透， 默认： false
							// image:'./image.png',//自定义图标的本地路径
						});
						this.setToken(res.result.token);
						this.setUserInfo(res.result.userInfo);
						this.setStoreId(this.currentIndex) //
						// uni.navigateBack({
						// 	delta: 1
						// })
						// console.log(this.word);
						if (this.word && this.word != 'null') {
							this.onGoodsDetail() //如果存在剪切板。调用接口绑定邀请码等信息
						} else {
							console.log("执行跳转操作", userInfo
								.belongStore);
							if (userInfo.belongStore != 1) {
								// uni.reLaunch({
								// 	url: "/pages/Invitation/Invitation"
								// })
								this.$refs.inviteDia.opens()
								this.$refs.inviteDia.getClipboardData()
							} else {
								uni.reLaunch({
									url: "/pages/index/index"
								})
							}
						}


					} else {
						this.$mesaage.error(res.result
							.message);
					}
				}).finally(() => {
					that.loading = false
				})
			},
			// IOS手机号一键登录
			getPhoneIOS() {
				if (this.status.length == 0) {
					uni.showToast({
						title: '请勾选用户协议',
						icon: 'none',
						duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
						mask: true, // 是否显示透明蒙层， 防止触摸穿透， 默认： false
					});
					return false
				}
				// let that = this
				uni.login({
					provider: 'apple',
					success: async (loginRes) => {
						console.log(loginRes);
						this.openids = loginRes.authResult.openid
						console.log(this.openids, 'this.openids')
						let results = await loginIosCheck({
							openId: this.openids
						})
						console.log(results, 'results')
						if (results.success) {
							if (results.result.isRegister == 0) {
								console.log("未");
								this.showing = true

							} else {
								console.log("已");
								this.confirmBtn()
							}
						}
						return
						// 登录成功
						uni.getUserInfo({
							provider: 'apple',
							success: (info) => {
								console.log(info, 1234);
								// 获取用户信息成功, info.authResult中保存登录认证数据

							}
						})

					},
					fail: (err) => {
						console.log(err);
						// 登录授权失败
						// err.code错误码参考`授权失败错误码(code)说明`
					}
				});
			},

			// 绑定登录信息
			onGoodsDetail() {
				getCodeItem(this.word && this.word != 'null').then(res => {
					console.log(res);
					this.setStoreId(res.result.store.id)
					// this.setStoreId(index) //设置店铺
					uni.reLaunch({
						url: `/pages/goodsdetail/goodsdetail?pkid=${res.result.storeGoods.id}&cart=1`
					})
				})
			},

			// 用户协议
			onUserAgreement() {
				this.$refs.UserAgreement.open('center')
			},

			// 隐私政策
			onPrivacyPolicy() {
				this.$refs.PrivacyPolicy.open('center')
			},

			dialogConfirm() {

			},

			dialogClose() {

			}
		},
	}
</script>

<style lang="scss" scoped>
	.center {
		position: relative;
		height: 100%;
		width: 100%;
		text-align: center;
		// background-color: pink;
		// background: url("@/static/background/background.png");
		// background-position: center center;
		// background-repeat: no-repeat;
		// background-attachment: fixed;
		// background-size: cover;



		.bgc {
			position: absolute;
			z-index: 1;
			width: 100%;
			height: 100%;

			.bac-sty {
				width: 100%;
				height: 100%;
			}
		}


		.chet_wrap {
			position: relative;
			z-index: 2;

			// 容器
			.shop_wrap {
				padding-top: 200rpx;

				.shop_img {
					width: 170rpx;
					height: 170rpx;
					border-radius: 50%;
				}
			}

			.shop_name {
				font-size: 45rpx;
				font-weight: 600;
				color: $uni-text-color-red;
				// font-family: "黑体";
				padding: 20rpx;
			}

			.shop-tel {
				font-size: 35rpx;
				font-weight: 600;
				padding: 10rpx;
			}

			.shop_desc {
				font-size: 25rpx;
				color: #9a9cab;
			}

			.shop-btn {
				width: 75%;
				height: 80rpx;
				line-height: 80rpx;
				background: linear-gradient(to right, #f21a1a, #ff7535);
				color: #fff;
				border-radius: 40rpx;
				font-size: 30rpx;
				margin: 50rpx auto;
			}

			.btn-wrap {
				margin-bottom: 20rpx;
				width: 75%;
				height: 70rpx;
				border-radius: 40rpx;
				margin: 0 auto;
				line-height: 70rpx;
				background: #eee;
				margin-bottom: 10rpx;

				// ios登录图标
				.btn-ios {
					display: flex;
					align-items: center;
					margin-right: 10rpx;
					justify-content: center;
					// padding:5rpx 20rpx;
					// width: max-content;
					// border-radius: 25rpx;
					// margin-left: 20%;
					// font-size: 25rpx;

					.ios-sty {
						width: 40rpx;
						height: 40rpx;
					}
				}
			}

			// .shop-btn-ios {
			// 	margin-bottom: 10rpx;
			// 	width: 75%;
			// 	height: 80rpx;
			// 	line-height: 80rpx;
			// 	border-radius: 40rpx;
			// 	font-size: 30rpx;
			// }

			.shop-check {
				color: #8c8ea0;
				font-size: 25rpx;
				padding-bottom: 30rpx;
			}

			.color_bule {
				color: #f58e27;
			}
		}


	}

	::v-deep .uni-popup__info {
		color: #000;
	}

	.popup-sty {
		height: 800rpx;
		overflow: auto;

		.T-top {
			margin-top: 20rpx;
		}

		.T-left {
			text-align: left;
			font-size: 22rpx;
		}

		.T-right {
			text-align: right;
			font-size: 22rpx;
		}

		.T-text {
			text-align: left;
			font-size: 22rpx;
		}
	}

	.phonePut {
		margin-top: 40rpx;

		::v-deep .u-input__content {
			border-bottom: 1px solid #000;
		}
	}
</style>